<script setup lang="ts">
import { computed, nextTick, onMounted, ref } from 'vue';

interface GuideStep {
  title: string;
  description: string;
  element: string;
  position: 'bottom' | 'left' | 'right' | 'top';
}

const props = defineProps<{
  autoStart?: boolean;
}>();

const emit = defineEmits<{
  (e: 'finish'): void;
  (e: 'skip'): void;
}>();

const showGuide = ref(false);
const currentStep = ref(0);
const currentElement = ref<HTMLElement | null>(null);

const steps: GuideStep[] = [
  {
    title: '欢迎来到朱氏皇族治理平台！',
    description: '这是一个基于区块链的家族数字文明平台，让我们开始探索吧！',
    element: '.logo',
    position: 'bottom',
  },
  {
    title: '查看族谱',
    description: '点击这里可以查看完整的朱氏皇族世系图，使用G6可视化技术展示',
    element: '[data-guide="genealogy"]',
    position: 'right',
  },
  {
    title: '祖先纪念堂',
    description: '在这里可以祭拜祖先、献花留言，生成链上存证',
    element: '[data-guide="shrine"]',
    position: 'right',
  },
  {
    title: '家族学堂',
    description: '学习家族知识、课程，完成后可获得"学者SBT"',
    element: '[data-guide="academy"]',
    position: 'right',
  },
  {
    title: '朝政治理',
    description: '参与家族提案投票，权重按角色分配（皇帝3票、藩王2票）',
    element: '[data-guide="governance"]',
    position: 'right',
  },
  {
    title: '个人中心',
    description: '点击这里查看您的SBT、投票记录、学习进度等',
    element: '.header-actions button',
    position: 'bottom',
  },
];

const tooltipStyle = computed(() => {
  if (!currentElement.value) return {};
  const rect = currentElement.value.getBoundingClientRect();
  const position = steps[currentStep.value].position;

  const style: any = {};
  const offset = 20;

  switch (position) {
    case 'bottom': {
      style.top = `${rect.bottom + offset}px`;
      style.left = `${rect.left + rect.width / 2}px`;
      style.transform = 'translateX(-50%)';
      break;
    }
    case 'left': {
      style.top = `${rect.top + rect.height / 2}px`;
      style.right = `${window.innerWidth - rect.left + offset}px`;
      style.transform = 'translateY(-50%)';
      break;
    }
    case 'right': {
      style.top = `${rect.top + rect.height / 2}px`;
      style.left = `${rect.right + offset}px`;
      style.transform = 'translateY(-50%)';
      break;
    }
    case 'top': {
      style.bottom = `${window.innerHeight - rect.top + offset}px`;
      style.left = `${rect.left + rect.width / 2}px`;
      style.transform = 'translateX(-50%)';
      break;
    }
  }

  return style;
});

const highlightStyle = computed(() => {
  if (!currentElement.value) return {};
  const rect = currentElement.value.getBoundingClientRect();
  return {
    top: `${rect.top - 4}px`,
    left: `${rect.left - 4}px`,
    width: `${rect.width + 8}px`,
    height: `${rect.height + 8}px`,
  };
});

onMounted(() => {
  if (props.autoStart && !localStorage.getItem('guide-completed')) {
    setTimeout(() => startGuide(), 1000);
  }
});

function startGuide() {
  showGuide.value = true;
  currentStep.value = 0;
  updateCurrentElement();
}

async function nextStep() {
  if (currentStep.value < steps.length - 1) {
    currentStep.value++;
    await nextTick();
    updateCurrentElement();
  }
}

function prevStep() {
  if (currentStep.value > 0) {
    currentStep.value--;
    updateCurrentElement();
  }
}

function updateCurrentElement() {
  const selector = steps[currentStep.value].element;
  currentElement.value = document.querySelector(selector);
}

function closeGuide() {
  // 点击遮罩不关闭，防止误操作
}

function skipGuide() {
  showGuide.value = false;
  emit('skip');
}

function finishGuide() {
  showGuide.value = false;
  localStorage.setItem('guide-completed', 'true');
  emit('finish');
}

defineExpose({ startGuide });
</script>

<template>
  <teleport to="body">
    <div v-if="showGuide" class="user-guide-overlay">
      <div class="guide-mask" @click="closeGuide"></div>
      <div
        class="guide-tooltip"
        :class="[`step-${currentStep}`]"
        :style="tooltipStyle"
      >
        <div class="guide-content">
          <h3>{{ steps[currentStep].title }}</h3>
          <p>{{ steps[currentStep].description }}</p>
          <div class="guide-actions">
            <a-button v-if="currentStep > 0" @click="prevStep">上一步</a-button>
            <a-button
              v-if="currentStep < steps.length - 1"
              type="primary"
              @click="nextStep"
            >
              下一步 ({{ currentStep + 1 }}/{{ steps.length }})
            </a-button>
            <a-button v-else type="primary" @click="finishGuide">
              完成引导
            </a-button>
            <a-button type="text" @click="skipGuide">跳过</a-button>
          </div>
        </div>
        <div class="guide-arrow"></div>
      </div>
      <div
        v-if="currentElement"
        class="highlight-element"
        :style="highlightStyle"
      ></div>
    </div>
  </teleport>
</template>

<style scoped lang="scss">
.user-guide-overlay {
  position: fixed;
  inset: 0;
  z-index: 9999;
  pointer-events: none;

  .guide-mask {
    position: absolute;
    inset: 0;
    pointer-events: all;
    background: rgb(0 0 0 / 50%);
  }

  .guide-tooltip {
    position: fixed;
    z-index: 10001;
    max-width: 350px;
    padding: 20px;
    pointer-events: all;
    background: white;
    border-radius: 8px;
    box-shadow: 0 4px 20px rgb(0 0 0 / 30%);

    .guide-content {
      h3 {
        margin: 0 0 12px;
        font-size: 16px;
        color: #1890ff;
      }

      p {
        margin: 0 0 16px;
        line-height: 1.6;
        color: #666;
      }

      .guide-actions {
        display: flex;
        gap: 8px;
        justify-content: flex-end;
      }
    }
  }

  .highlight-element {
    position: fixed;
    z-index: 10000;
    pointer-events: none;
    border: 2px solid #1890ff;
    border-radius: 4px;
    box-shadow: 0 0 0 4px rgb(24 144 255 / 20%);
    animation: pulse 2s infinite;
  }
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgb(24 144 255 / 70%);
  }

  70% {
    box-shadow: 0 0 0 10px rgb(24 144 255 / 0%);
  }

  100% {
    box-shadow: 0 0 0 0 rgb(24 144 255 / 0%);
  }
}
</style>
